#!/usr/bin/python3
#-*- coding:UTF-8 -*-
"""
@file            dump-maker.py
@author          mening
@date            2024-01-15 11:27:49
@copyright       Copyright (c) 2024 by 北京长扬科技有限公司, ALL Rights Reserved.
@details         这里仿照abichecker.py文件,将rpm包cpio解压的基础库文件生成dump文件.
"""
import os
import re

"""全局变量"""


def get_sofile_name(sofilename):
    """
    get the .so file name
    ie: foo.so.0.0 -> foo.so
    """
    return  re.findall(r'.*.so', sofilename)[0]

def dumper_by_debuginfo(work_path):
    """
    generate .dump file by debuginfo .rpm file
    """
    cnt = 0
    cnt_basic = 0
    os.chdir(work_path)
    path_usr_lib64 = work_path + '/usr/lib64'
    path_lib64 = work_path + '/lib64'
    path_usr_lib = work_path + '/usr/lib'
    path_lib = work_path + '/lib'
    print(path_lib)
    print(path_usr_lib)
    print(path_usr_lib64)
    print(path_lib64)
    sofiles = []
    for root, dirs, files in os.walk(work_path+'/usr'):
        for eachfile in files:
            full_file = os.path.join(root, eachfile)
            if re.match(r'.*\.so.*', eachfile) and not os.path.islink(full_file) and not os.path.isdir(full_file):
                sofiles.append(full_file)
                print(full_file)

    print('[debug]:获取了库文件的列表了')

    if len(sofiles) > 0:
        for sofile in sofiles:
            """
            (sofile_path, sofile_name) = os.path.split(sofile)
            先不着急生成dump,打印一下或者统计一下有多少个so看看再说
            """
            (sofile_path, sofile_name) = os.path.split(sofile)
            """
            print(sofile)
            print(sofile_path)
            """           
            print(sofile+" : "+sofile_path)
            if (path_usr_lib64 == sofile_path) or (path_lib64 == sofile_path) or (path_lib == sofile_path) or (path_usr_lib == sofile_path):
                """sofile_name = get_sofile_name(sofile_name)"""
                if not os.path.exists("ABIDUMP/ABI-{}.dump".format(sofile_name)):
                    os.system('abi-dumper ' + sofile + ' --search-debuginfo=' + work_path + '/usr/lib/debug/' + ' -o ABIDUMP/' + 'ABI-' + sofile_name + '.dump')
                else:
                    print("skip Create dump ABI-"+sofile_name)
                print("Fount .so file named: %s" %sofile)
                cnt_basic += 1
            cnt += 1
        print("Found .so file in basic path:%d" %cnt_basic)
        print("Found .so file :%d" %cnt)

if __name__ == '__main__':
    """
    main
    1. create a directory named sys.argv[1] (libfoo) in sys.argv[2] (/root/checkdir/);
    2. put the rpm files and debuginfo files of 2 versions in libfoo;
    3. run 'python abichecker.py 'libfoo' '/root/checkdir/'
    4. the results are saved in /root/checkdir/libfoo/compat_reports
    """
    dumper_by_debuginfo(os.getcwd())